const game = document.querySelector('.game');
const gameWidth = game.clientWidth;
class Pipe extends Rectangle{
    isExited = true;
    constructor(height, top, speed, dom){
        super(52, height, gameWidth, top, speed, 0, dom);
    }
    onMove(){

        if(this.x < -this.width){
            this.dom.remove();
            this.isExited = false;
        }
    }

    
}

function getRandomNumber(min, max){
    return Math.floor(Math.random() * (max - min)) + min;
}

class PipePare{
    stopTimer = null;
    
    constructor(speed){
        this.up = document.createElement('div');
        this.down = document.createElement('div');
        this.up.classList.add('pipeUp');
        this.down.classList.add('pipeDown');
        game.appendChild(this.up);
        game.appendChild(this.down);

        this.spaceHeihgt = 150;  // 柱子之間的空隙 
        const fristPipeHeight = getRandomNumber(0, 488-150);

        this.upPipe = new Pipe(fristPipeHeight, 0, speed, this.up);
        this.downPipe = new Pipe(338 - fristPipeHeight, 150 + fristPipeHeight, speed, this.down);
    }
    stop(){
        if(this.stopTimer){
            clearInterval(this.stopTimer);
            this.stopTimer = null;
        }
        this.down.remove();
        this.up.remove();
    }

    move(duration){
        this.stopTimer = setInterval( () => {
            this.upPipe.move(duration);
            this.downPipe.move(duration);
        },10)
    }

    isCollision(bird){
        const birdStyle = getComputedStyle(document.querySelector('.bird'))
        let y = Number.parseInt(birdStyle.top);
        if(this.upPipe.x < bird.x + bird.width && this.upPipe.x > bird.x){
            return y < this.upPipe.height || y + bird.height > this.upPipe.height + this.spaceHeihgt;
        }
    }
}

class GamePipePair{
    pipeTimer = null;
    pipeArr = [];  // 用于显示的管道数组
    // 记录小鸟越过的数组
    scoreArr = [];
    constructor(speed){
        this.speed = speed;
        this.pair = new PipePare(speed);
        this.init();
    }

    init(){
        this.pipeTimer = setInterval( ()=> {
            let tmp = new PipePare(this.speed);
            tmp.move(0.01);
            this.pipeArr.push(tmp);
            this.scoreArr.push(tmp);
        }, 2000) 
    }

    getScore(bird){
        return this.scoreArr.filter(item => item.upPipe.x <= bird.x).length;
    }

    stop(){
        this.pipeArr.forEach(item => {
            item.stop();
        })
        if(this.pipeTimer){
            clearInterval(this.pipeTimer);
            this.pipeTimer = null;
        }
    }

    collisionDetection(bird){  // 小鸟对象传入
        this.pipeArr = this.pipeArr.filter(item => item.upPipe.isExited); // 过滤掉了不存在的
        // 检查小鸟是否碰撞到柱子
        for(let i = 0 ;i < this.pipeArr.length;i++){
            if(this.pipeArr[i].isCollision(bird)){
                return true;
            }
        }
        return false;
    }
    
}